<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="/WEB-INF/webpage/common/taglibs.jspf" %>
<!DOCTYPE html>
<html>
<head>
    <title>装箱关联</title>
    <meta name="decorator" content="grid-select"/>
    <script src="${staticPath}/common/js/func.js"></script>
</head>
<body title="<spring:message code="cc.zcdMx.title" />">
<grid:grid id="ccZcdMxGridId" url="${adminPath}/cc/zcd/mx/zcdMxAjaxList?zhuangcdNo=${zcdHz.zhuangcdNo}"
           shrinkToFit="false" rowNum="100" height="250" editable="true">
    <%-- 装车单状态为未关联或者已关联时才可以进行关联操作 --%>
    <c:if test="${zcdHz.state == '0' || zcdHz.state == '1'}">
        <grid:column label="关联操作" name="opt" formatter="button" width="120" sortable = "false"/>
        <grid:button title="设备" groupname="opt"
                     onclick="zcdMxRowDialogSetValueForGrid('设备关联', '${adminPath}/cc/zcd/mx/deviceList?zhuangcdNos=${zcdHz.zhuangcdNo}', 'ccZcdMxGridIdGrid', 'ccZcdMxDeviceGridIdGrid', '1000px', '500px', 'id,no,electric,collectTime', 'sbSn,sbNo,electric,collectTime')"
                     outclass="btn-primary"/>
        <grid:button title="冷藏箱" groupname="opt"
                     onclick="zcdMxRowDialogSetValueForGrid('冷藏箱关联', '${adminPath}/cc/zcd/mx/couvenseList?zhuangcdNos=${zcdHz.zhuangcdNo}', 'ccZcdMxGridIdGrid', 'ccZcdMxCouvenseGridIdGrid', '1000px', '500px', 'id,no', 'boxSn,boxNo')"
                     outclass="btn-primary"/>
    </c:if>
    <grid:column label="cc.zcdMx.sbSn" name="sbSn" hidden="true" width="80"/>
    <grid:column label="cc.zcdMx.sbSn" name="sbNo" width="80"/>
    <grid:column label="cc.device.electric" name="electric" width="80"/>
    <grid:column label="cc.zcdMx.boxSn" name="boxSn" hidden="true" width="90"/>
    <grid:column label="cc.zcdMx.boxSn" name="boxNo" width="90"/>
    <grid:column label="cc.zcdHz.zhuangcdNo" name="zhuangcdNo" width="120"/>
    <grid:column label="cc.zcdMx.zhuangcdId" name="zhuangcdId" width="140"/>
    <grid:column label="cc.zcdMx.liushBarcode" name="liushBarcode"/>
    <grid:column label="cc.zcdMx.ywbm" name="ywbm" width="80"/>
    <grid:column label="cc.zcdMx.danjNo" name="danjNo" width="110" query="true" condition="like"/>
    <grid:column label="cc.zcdMx.huozName" name="huozName" width="120"/>
    <grid:column label="cc.zcdMx.shangpNo" name="shangpNo" width="100"/>
    <grid:column label="cc.zcdMx.chineseName" name="chineseName"/>
    <grid:column label="cc.zcdMx.tongyName" name="tongyName" width="80"/>
    <grid:column label="cc.zcdMx.shijJs" name="shijJs" width="60"/>
    <grid:column label="cc.zcdMx.shijLss" name="shijLss" width="60"/>
    <grid:column label="cc.zcdMx.shijNum" name="shijNum" width="60"/>
    <grid:column label="cc.zcdMx.baozNum" name="baozNum" width="60"/>
    <grid:column label="cc.zcdMx.lot" name="lot" width="100"/>
    <grid:column label="cc.zcdMx.youxDate" name="youxDate"/>
    <grid:column label="cc.humiture.collectTime" name="collectTime" width="160" hidden="true"/>

    <%-- 拥有管理员权限的用户，并且装车单状态为未关联的才可以编辑修改商品温度 --%>
    <%--<shiro:hasRole name="admin">--%>
    <c:choose>
        <c:when test="${zcdHz.state == '1' || zcdHz.state == '0' }">
            <grid:column label="cc.zcdMx.wendMin" name="wendMin" editable="true"/>
            <grid:column label="cc.zcdMx.wendMax" name="wendMax" editable="true"/>
        </c:when>
        <c:otherwise>
            <grid:column label="cc.zcdMx.wendMin" name="wendMin"/>
            <grid:column label="cc.zcdMx.wendMax" name="wendMax"/>
        </c:otherwise>
    </c:choose>

    <grid:column label="cc.zcdMx.danwName" name="danwName"/>
    <grid:column label="cc.zcdMx.address" name="address"/>
    <grid:column label="cc.zcdMx.czry" name="czry" width="60"/>
    <grid:column label="cc.zcdMx.beginDate" name="beginDate"/>
    <grid:column label="cc.zcdMx.endDate" name="endDate"/>
    <grid:column label="cc.zcdMx.dwId" name="dwId" width="100"/>

    <%-- 拥有管理员权限的用户，并且装车单状态为未关联的才可以编辑修改商品温度 --%>
    <shiro:hasPermission name="cc:zcd:updProdsTemp">
        <c:if test="${zcdHz.state == '1' || zcdHz.state == '0' }">
            <grid:toolbar title="修改商品温度" icon="fa-file-text-o" btnclass="btn-primary" onclick="updProdsTemp()"/>
        </c:if>
    </shiro:hasPermission>

    <shiro:hasPermission name="cc:zcd:orderSplitNumber">
        <c:if test="${zcdHz.state == '0' }">
            <grid:toolbar title="明细拆分" icon="fa-file-text-o" btnclass="btn-primary" onclick="orderSplitNumber()"/>
        </c:if>
    </shiro:hasPermission>

    <grid:toolbar function="search"/>
    <grid:toolbar function="reset"/>
</grid:grid>

<script type="text/javascript">
    /**
     * 父页面点击确定时触发的事件
     */
    function confirm(callback) {
        <%-- 装车单状态为3：配送完成，直接返回 --%>
        <c:if test="${zcdHz.state == '3' }">
        if (typeof callback == "function") {
            callback();
        }
        return;
        </c:if>

        <%-- 装车单状态为2：已激活，可操作修改明细时间 --%>
        <c:if test="${zcdHz.state == '2' }">
        if (typeof callback == "function") {
            callback();
        }
        return;
        </c:if>

        <%-- 装车单状态为0：未关联，1：已关联，可进行关联操作 --%>
        <c:if test="${zcdHz.state == '0' || zcdHz.state == '1'}">
        // 将选中的行取消编辑状态，否则获取的数值不是本身的数值
        $("#ccZcdMxGridIdGrid").jqGrid('saveRow', ccZcdMxGridIdLastSelection);

        let rowsData = $("#ccZcdMxGridIdGrid").jqGrid('getRowData');
        // 判断一个流水号是否关联了多个设备以及保温箱
        for (let i = 0; i < rowsData.length; i++) {
            for (let j = 0; j < rowsData.length; j++) {
                // 判断一个流水号关联了多个采集设备或者保温箱
                if (rowsData[i].liushBarcode == rowsData[j].liushBarcode) {
                    if (rowsData[i].sbSn != rowsData[j].sbSn
                            || rowsData[i].boxSn != rowsData[j].boxSn) {
                        top.layer.alert('一个流水号关联了多个采集设备或者保温箱，请确认后重新关联!', {icon: 0, title: '警告'});
                        return;
                    }
                }
                // 判断本次关联中是否存在一个保温箱下是否存在温度范围不同的商品
                if (rowsData[i].boxSn == rowsData[j].boxSn
                        && (rowsData[i].wendMin != rowsData[j].wendMin || rowsData[i].wendMax != rowsData[j].wendMax)) {
                    top.layer.alert('保温箱' + rowsData[i].boxNo + '内存在温度储存范围不同的商品', {icon: 0, title: '警告'});
                    return;
                }
                // 判断本次关联中是否存在一个设备关联了多个保温箱
                if (rowsData[i].sbSn == rowsData[j].sbSn
                        && rowsData[i].boxSn != rowsData[j].boxSn) {
                    top.layer.alert('设备' + rowsData[i].sbNo + '关联了多个保温箱', {icon: 0, title: '警告'});
                    return;
                }
            }
        }

        // 创建采集设备，保温箱，流水号关联关系
        let relations = [];
        let electricAlarm = ${electricAlarm};
        let electricWarning = ${electricWarning};
        let electricWarningList = [];
        let warningContent = '';
        for (let i = 0; i < rowsData.length; i++) {
            if (!isNull(rowsData[i].sbSn)
                    && !isNull(rowsData[i].boxSn)) {
                if (rowsData[i].zhuangcdNo.startsWith("DSF")) {
                    top.layer.alert('第三方装车单不用关联!', {icon: 0, title: '警告'});
                    return;
                }
                else {
                    // 未关联状态的单据才判断电量
                    <c:if test="${zcdHz.state == '0'}">
                        if (rowsData[i].electric <= electricAlarm) {
                            top.layer.alert(rowsData[i].sbNo + '电量为' + rowsData[i].electric
                                + '低于阈值' + electricAlarm + ",不允许关联!", {icon: 0, title: '警告'});
                            return;
                        }
                        if (rowsData[i].electric > electricAlarm && rowsData[i].electric <= electricWarning) {
                            if (warningContent.indexOf(rowsData[i].electric) < 0) {
                                warningContent = warningContent + rowsData[i].sbNo + '电量为' + rowsData[i].electric
                                    + '低于阈值' + electricWarning + "；<br/>";
                            }
                            electricWarningList.push(i);
                        }

                        relations.push({
                            liushBarcode: rowsData[i].liushBarcode.trim(),
                            cjId: rowsData[i].sbSn.trim(),
                            lcSn: rowsData[i].boxSn.trim(),
                            electricWarning: electricWarningList.length > 0 ? true : false,
                            electricValue: rowsData[i].electric.trim(),
                            collectTime: rowsData[i].collectTime.trim()
                        });
                    </c:if>
                    // 已关联状态的先不判断了
                    <c:if test="${zcdHz.state != '0'}">
                        relations.push({
                            liushBarcode: rowsData[i].liushBarcode.trim(),
                            cjId: rowsData[i].sbSn.trim(),
                            lcSn: rowsData[i].boxSn.trim(),
                            electricWarning: false,
                        });
                    </c:if>

                }
            }
            else {
                top.layer.alert('存在未关联采集设备以及保温箱的明细，请确认后重新关联!', {icon: 0, title: '警告'});
                return;
            }
        }

        if (electricWarningList.length > 0) {
            top.layer.open({
                area: [300, 200],
                title: "电量预警",
                btn: ['确定', '取消'],
                content: warningContent + "请确认是否关联！",
                yes: function(index, layero) {
                    // POST请求操作关联
                    $.ajax({
                        type: "POST",
                        url: "${adminPath}/cc/zcd/mx/relation",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify(relations),
                        dataType: "json",
                        success: function (data) {
                            top.layer.alert(data.msg, {icon: 0, title: '提示'});
                            if (data.ret == 0) {
                                // 最后调用回调函数，关闭对话框
                                if (typeof callback == "function") {
                                    callback();
                                }
                            }
                        }
                    });
                    setTimeout(function(){top.layer.close(index)}, 100)
                },
                cancel: function(index){
                    for (let i = 0; i < electricWarningList.length; i++) {
                        $("#ccZcdMxGridIdGrid").jqGrid('setCell', electricWarningList[i] + 1, 'sbSn', '', '', '', true);
                        $("#ccZcdMxGridIdGrid").jqGrid('setCell', electricWarningList[i] + 1, 'sbNo', '', '', '', true);
                        $("#ccZcdMxGridIdGrid").jqGrid('setCell', electricWarningList[i] + 1, 'electric', '', '', '', true);
                        $("#ccZcdMxGridIdGrid").jqGrid('setCell', electricWarningList[i] + 1, 'collectTime', '', '', '', true);
                    }
                    return
                }
            });
        }
        else {
            // POST请求操作关联
            $.ajax({
                type: "POST",
                url: "${adminPath}/cc/zcd/mx/relation",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(relations),
                dataType: "json",
                success: function (data) {
                    top.layer.alert(data.msg, {icon: 0, title: '提示'});
                    if (data.ret == 0) {
                        // 最后调用回调函数，关闭对话框
                        if (typeof callback == "function") {
                            callback();
                        }
                    }
                }
            });

        }
        </c:if>
    }

    /**
     * 更新商品温度
     */
    function updProdsTemp() {
        $("#ccZcdMxGridIdGrid").jqGrid('saveRow', ccZcdMxGridIdLastSelection);
        var selectedRows = $("#ccZcdMxGridIdGrid").jqGrid('getGridParam', 'selarrrow');
        // 如果没有选择，提示
        if (selectedRows.length < 1) {
            top.layer.alert('请先选择要修改的商品温度明细!', {icon: 0, title: '警告'});
            return;
        }

        // 如果是已关联状态，需要判断是不是第三方装车单
        if ('${zcdHz.state }' != '1' && '${zcdHz.state }' != 0) {
            top.layer.alert('只有未关联状态或者已关联状态的单据才可以修改温度界限！', {icon: 0, title: '警告'});
            return;
        }

        var url = "${adminPath}/cc/zcd/mx/updProdsTemp";
        // 如果是已关联状态，需要判断是不是第三方装车单
        if ('${zcdHz.zhuangcdNo }'.indexOf('DSF') == 0) {
            url = "${adminPath}/cc/zcd/mx/updProdsTempDSF";
        }

        // 获取商品名以及商品温度上下限
        var rowData;
        var prodsTemp = [];
        for (var i = 0; i < selectedRows.length; i++) {
            rowData = $("#ccZcdMxGridIdGrid").jqGrid('getRowData', selectedRows[i]);
            // 判断最高温或最低温是不是有值
            if (isNull(rowData.wendMin) || isNull(rowData.wendMax)) {
                top.layer.alert('请输入商品最高温或最低温!', {icon: 0, title: '警告'});
                return;
            }
            // 判断最高温或者最低温是不是已经编辑完毕，即已经按了Enter键
            if (rowData.wendMin.indexOf("input") >= 0) {
                top.layer.alert('请先按Enter键将编辑后的值保存!', {icon: 0, title: '警告'});
                return;
            }
            if (parseFloat(rowData.wendMin) - parseFloat(rowData.wendMax) > 0) {
                top.layer.alert('商品' + rowData.shangpNo + '存储温度不合理，请确认后重新输入!', {icon: 0, title: '警告'});
                return;
            }
            if ('${zcdHz.zhuangcdNo }'.indexOf('DSF') == 0) {
                prodsTemp.push({
                    boxSn: rowData.boxSn.trim(),
                    wendMin: rowData.wendMin.trim(),
                    wendMax: rowData.wendMax.trim()
                });
            }
            else {
                prodsTemp.push({
                    shangpNo: rowData.shangpNo.trim(),
                    wendMin: rowData.wendMin.trim(),
                    wendMax: rowData.wendMax.trim()
                });
            }
        }

        // POST请求操作关联
        $.ajax({
            type: "POST",
            url: url,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(prodsTemp),
            dataType: "json",
            success: function (data) {
                top.layer.alert(data.msg, {icon: 0, title: '提示'});
                if (data.ret == 0) {
                    //刷新表单
                    refreshTable("ccZcdMxGridIdGrid");
                }
            }
        });
    }

    /**
     * 装车单拆分,填写拆分个数
     */
    function orderSplitNumber() {
        var selectedRows = $("#ccZcdMxGridIdGrid").jqGrid('getGridParam', 'selarrrow');
        // 如果没有选择，提示
        if (selectedRows.length != 1) {
            top.layer.alert('请选择一条明细进行订单拆分!', {icon: 0, title: '警告'});
            return;
        }

        // 获取数据
        var zcd = $("#ccZcdMxGridIdGrid").jqGrid('getRowData', selectedRows[0]);
        // 如果装车单状态不为0:未关联 1:已关联，不允许关联冷藏车
        if (zcd.shijJs < 2) {
            top.layer.alert('该订单不支持拆分!', {icon: 0, title: '警告'});
            return;
        }

        // 打开交接页面，选择需要交接的单据以及交接时间
        openDialogCommit("装车单拆分", "${adminPath}/cc/zcd/mx/orderSplitNumber?zhuangcdId=" + zcd.zhuangcdId + "&shijJs=" + zcd.shijJs, "ccZcdMxGridIdGrid", "500px", "300px");

    }

    /**
     * 明细界面
     */
    function zcdMxRowDialogSetValueForGrid(title, url, gridId, childGridId, width, height, fromAttr, toAttr) {
        rowDialogSetValueForGrid(title, url, gridId, childGridId, width, height, fromAttr, toAttr, function(rtnVal) {
            // 相同流水号的自动赋值
            $("#ccZcdMxGridIdGrid").jqGrid('saveRow', ccZcdMxGridIdLastSelection);
            let rowsData = $("#ccZcdMxGridIdGrid").jqGrid('getRowData');
            let selectedRows = $("#ccZcdMxGridIdGrid").jqGrid('getGridParam', 'selarrrow');
            let rowData;
            let toAttrList = toAttr.split(",");
            for (let i = 0; i < selectedRows.length; i++) {
                rowData = $("#ccZcdMxGridIdGrid").jqGrid('getRowData', selectedRows[i]);
                for (let j = 0; j < rowsData.length; j++) {
                    if (rowsData[j].liushBarcode == rowData.liushBarcode) {
                        for (let k = 0; k < toAttrList.length; k++) {
                            $("#ccZcdMxGridIdGrid").jqGrid('setCell', j + 1, toAttrList[k], rowsData[j][toAttrList[k]])
                        }
                    }
                }
            }
        });
    }

</script>

</body>

</html>